package cn.t212.cloud.ms.client;

import com.sun.xml.internal.messaging.saaj.util.Base64;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Util;

import java.nio.charset.Charset;

public class FeignRequestInterceptor implements RequestInterceptor {
    private final String headerValue;

    public FeignRequestInterceptor(String username, String password) {
        this(username, password, Util.ISO_8859_1);
    }

    public FeignRequestInterceptor(String username, String password, Charset charset) {
        Util.checkNotNull(username, "username", new Object[0]);
        Util.checkNotNull(password, "password", new Object[0]);
        this.headerValue = "Basic " + base64Encode((username + ":" + password).getBytes(charset));
    }

    private static String base64Encode(byte[] bytes) {
        return new String(Base64.encode(bytes));
    }

    public void apply(RequestTemplate template) {
        System.out.println("========"+ headerValue);
        template.header("Authorization", new String[]{this.headerValue});
    }
}
